#include <jni.h>
#include <string>
#include <jni.h>

template<typename T>
int partition(T *arr, int left, int right) {
    T pivot = arr[left];

    while (left < right) {
        while (left < right && arr[right] > pivot)right--;
        arr[left] = arr[right];
        while (left < right && arr[left] <= pivot)left++;
        arr[right] = arr[left];
    }
    arr[left] = pivot;
    return left;
}

template<typename T>
void quickSort(T *arr, int left, int right) {
    if (left < right) {
        int pivot = partition(arr, left, right);
        quickSort(arr, left, pivot - 1);
        quickSort(arr, pivot + 1, right);
    }
}

extern "C" jobjectArray
Java_com_example_study_page_fragment_NativeFragment_quickSort(JNIEnv *env, jobject thiz,
                                                              jobjectArray list) {
    jsize len = env->GetArrayLength(list);

    jintArray intArray = env->NewIntArray(len);
    // 将传入的包装类型数组中的元素复制到intArray中
    for (int i = 0; i < len; i++) {
        jobject element = env->GetObjectArrayElement(list, i);
        jint value = env->CallIntMethod(element,
                                        env->GetMethodID(env->GetObjectClass(element), "intValue",
                                                         "()I"));
        env->SetIntArrayRegion(intArray, i, 1, &value);
    }

    // 对intArray进行排序
    jint *arrayElements = env->GetIntArrayElements(intArray, nullptr);
    quickSort<jint>(arrayElements, 0, len - 1);

    // 将排序后的intArray的元素复制回传入的包装类型数组list
    for (int i = 0; i < len; i++) {
        jint value = arrayElements[i];
        jobject element = env->NewObject(env->FindClass("java/lang/Integer"),
                                         env->GetMethodID(env->FindClass("java/lang/Integer"),
                                                          "<init>", "(I)V"), value);
        env->SetObjectArrayElement(list, i, element);
        env->DeleteLocalRef(element);
    }

    env->DeleteLocalRef(intArray);
    return list;
}